Solution for experiment of a die exercise


In [1]:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utils import comp_prob_inference

In [2]:
finite_prob_space_die = {"1":1/6, "2":1/6, "3":1/6, "4":1/6, "5":1/6, "6":1/6}

In [3]:
sum(finite_prob_space_die.values())


Out[3]:
0.9999999999999999

In [4]:
#throw single die
def throw_die():
    finite_prob_space_die = {"1":1/6, "2":1/6, "3":1/6, "4":1/6, "5":1/6, "6":1/6}
    return comp_prob_inference.sample_from_finite_probability_space(finite_prob_space_die)
throw_die()


Out[4]:
'5'

In [5]:
from utils.comp_prob_inference import sample_from_finite_probability_space

def throw_die_n_times(number_of_throws):
    finite_prob_space_die = {"1":0.16666666666666666,
                        "2":0.16666666666666666,
                        "3":0.16666666666666666,
                        "4":0.16666666666666666,
                        "5":0.16666666666666666,
                        "6":0.16666666666666666}
    return [sample_from_finite_probability_space(finite_prob_space_die)
            for i in range(number_of_throws)]

throw_die_n_times(5)


Out[5]:
['1', '5', '5', '6', '6']

In [6]:
throws = throw_die_n_times(100)
comp_prob_inference.plot_discrete_histogram(throws, frequency=True)


for n = 100000


In [7]:
# TODO: make this plot more beautiful(with grids and color) and should be able to show value on hover
throws = throw_die_n_times(100000)
comp_prob_inference.plot_discrete_histogram(throws, frequency=True)



In [8]:
n = 100000
sixes_so_far = 0
fraction_of_six_occurence = []
for i in range(n):
    if throw_die() == '6':
        sixes_so_far += 1
    fraction_of_six_occurence.append(sixes_so_far / (i+1))

In [9]:
plt.figure(figsize=(8, 4))
plt.plot(range(1, n+1), fraction_of_six_occurence)
plt.xlabel('Number of throws')
plt.ylabel('Fraction of sixes')


Out[9]:
<matplotlib.text.Text at 0x7fcd59416080>

Indeed, we got stable line at the fraction $1/6$, which is probability of each face